

package com.sgu6.sgu6_machine.ui.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sgu6.middleware.enums.MachineCmdEnum;
import com.sgu6.middleware.enums.MachineStatusEnum;
import com.sgu6.middleware.event.DataRefreshEvent;
import com.sgu6.middleware.event.MachineIdEvent;
import com.sgu6.middleware.event.MachineStatusEvent;
import com.sgu6.middleware.event.WarningEvent;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.serialport.manager.SerialPortManager;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.adapter.RiceAdapter;
import com.sgu6.sgu6_machine.base.BaseF;
import com.sgu6.sgu6_machine.common.Constant;
import com.sgu6.sgu6_machine.container.ComContainer;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.db.DBManager;
import com.sgu6.sgu6_machine.dto.GoodsSimpleDto;
import com.sgu6.sgu6_machine.dto.ListGoodsSimpleDto;
import com.sgu6.sgu6_machine.event.SelectTypeEvent;
import com.sgu6.sgu6_machine.event.UpdateGoodsInfoEvent;
import com.sgu6.sgu6_machine.listener.OnDiaDismissListener;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.service.ComS;
import com.sgu6.sgu6_machine.ui.dialog.EnableCardDialogF;
import com.sgu6.sgu6_machine.ui.dialog.RechargeDialogF;
import com.sgu6.sgu6_machine.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class SelectF extends BaseF implements RiceAdapter.OnItemClickListener, View.OnTouchListener {

    @BindView(R.id.rvRice)
    RecyclerView rvRice;
    @BindView(R.id.overlay)
    RelativeLayout overlay;
    @BindView(R.id.btnMemberRecharge)
    TextView btnMemberRecharge;
    @BindView(R.id.btnEnableCard)
    TextView btnEnableCard;
    @BindView(R.id.tv_variety)
    TextView tvVariety;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_vip_price)
    TextView tvVipPrice;

    private List<GoodsSimpleDto> goods = new ArrayList<>();
    private RiceAdapter adapter;
    boolean pageClick = true;
    private MachineP machineP = new MachineP();
    private ComS comS;
    private ServiceConnection conn;
    private ListGoodsSimpleDto listGoodsSimpleDto;
    private DialogFragment enableCardDialogF, rechargeDialogF;

    public static SelectF newInstance(String params) {
        return new SelectF();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_select, container, false);
        unbinder = ButterKnife.bind(this, v);

        conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder binder) {
                ComS.MachineBinder myBinder = (ComS.MachineBinder) binder;
                comS = myBinder.getService();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.i(TAG, "onServiceDisconnected: ");
            }
        };


        requireContext().bindService(new Intent(requireContext(), ComS.class), conn, Context.BIND_AUTO_CREATE);

        adapter = new RiceAdapter(requireContext(), goods);
        adapter.setOnClickListener(this);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            rvRice.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
        } else {
            rvRice.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false));
        }
        rvRice.setAdapter(adapter);
        overlay.setOnTouchListener(this);
        try {
            listGoodsSimpleDto = DBManager.getInstance(requireContext()).queryMachineGoods().get(0);
            List<GoodsSimpleDto> tmp = listGoodsSimpleDto.goodsSortDtoList;

            goods.addAll(tmp);
            tvPrice.setText(goods.get(0).getPrice() + "元/斤");
            tvVipPrice.setText("充值享低至" + goods.get(0).getMarketPrice() + "元/斤");
            tvVariety.setText("品种:" + goods.get(0).getVarietyName());
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            Log.i(TAG, "onCreateView: ");
        }
        init();
        return v;
    }

    // FIXME: 2019-07-11 修改为从redis取数据，图片下载到本地即先从本地加载图片
    private void init() {
        machineP.getGoodsByMachineId(MachineContainer.machineConfigDto.machineNo);
    }


    //更新数据
    public void notifyUi(List<GoodsSimpleDto> goodsSimpleDtos) {
        try {
            goods.clear();
            goods.addAll(goodsSimpleDtos);
            Collections.sort(goods);
            adapter.notifyDataSetChanged();
            tvPrice.setText(goodsSimpleDtos.get(0).getPrice() + "元/斤");
            tvVipPrice.setText("充值享低至" + goodsSimpleDtos.get(0).getMarketPrice() + "元/斤");
            tvVariety.setText("品种:" + goodsSimpleDtos.get(0).getVarietyName());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //管理后台点刷新按钮
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataRefreshEvent(DataRefreshEvent event) {
        machineP.getGoodsByMachineId(MachineContainer.machineConfigDto.machineNo);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMachineStatusEvent(MachineStatusEvent event) {
        if (event.statusCode == MachineStatusEnum.待机.code()) {
            pageClick = false;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMachineIDEvent(MachineIdEvent event) {
        if (event.isUpdate) {
            machineP.getGoodsByMachineId(event.machineNo);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateGoodsInfoEvent(UpdateGoodsInfoEvent event) {
        try {
            listGoodsSimpleDto = event.goodsSortDtoList.get(0);
            if (goods.size() == 0) {
                DBManager.getInstance(requireContext()).insertMachineGoods(listGoodsSimpleDto);
            } else {
                DBManager.getInstance(requireContext()).updateMachineGoods(listGoodsSimpleDto);
            }
            notifyUi(listGoodsSimpleDto.getGoodsSortDtoList());
            MachineContainer.orderInfoCacheDto.setBarnId(event.goodsSortDtoList.get(0).barnId);
            MachineContainer.orderInfoCacheDto.setMachineNo(MachineContainer.machineConfigDto.machineNo);
        } catch (Exception e) {
            Log.i(TAG, "onUpdateGoodsInfoEvent: ");
        }

    }

    @Override
    public void onItemClick(int position) {
        try {
            MachineContainer.barnId = listGoodsSimpleDto.getBarnId();
            MachineContainer.riceName = goods.get(position).getName();
            if (!pageClick) {
                if (MachineContainer.machineTempOK) {
                    if (MachineContainer.MACHINE_STATUS == MachineStatusEnum.待机.code()) {
                        EventBus.getDefault().post(new SelectTypeEvent(goods.get(position)));
                        MachineContainer.categoryId = goods.get(position).getCategoryId();

                        String cmd;
                        if (MachineContainer.categoryId.equals(Constant.JING_MI)) {
                            cmd = MachineCmdEnum.精米.code();
                        } else if (MachineContainer.categoryId.equals(Constant.PEI_MI)) {
                            cmd = MachineCmdEnum.胚芽米.code();
                        } else if (MachineContainer.categoryId.equals(Constant.CAO_MI)) {
                            cmd = MachineCmdEnum.糙米.code();
                        } else {
                            cmd = MachineCmdEnum.胚芽米.code();
                        }
                        StringBuilder sb = new StringBuilder(cmd);
                        //5AA509820043000100070000
                        sb.replace(15, 16, String.valueOf(MachineContainer.barnCmd));
                        //发送调节精度指令
                        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(sb.toString()));
                    } else if (MachineContainer.MACHINE_STATUS == MachineStatusEnum.离线.code()) {
                        ToastUtil.showLongToast(requireContext(), "机器离线请稍后再试!");
                    } else if (MachineContainer.MACHINE_STATUS == MachineStatusEnum.停机.code()) {
                        ToastUtil.showLongToast(requireContext(), "机器停机请稍后再试!");
                    } else if (MachineContainer.MACHINE_STATUS == MachineStatusEnum.打米中.code()) {
                        ToastUtil.showLongToast(requireContext(), "机器碾米中请稍后再试!");
                    } else if (MachineContainer.MACHINE_STATUS == MachineStatusEnum.调节精度.code()) {
                        ToastUtil.showLongToast(requireContext(), "机器调节精度请稍后再试!");
                    }
                } else {
                    ToastUtil.showShortToast(requireContext(), "温度初始化,请稍后再试");
                }
            } else {
                ToastUtil.showShortToast(requireContext(), "机器离线暂不支持购买。");
            }
        } catch (Exception e) {
            Log.i(TAG, "onItemClick: " + e.getLocalizedMessage());
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWarningEvent(WarningEvent event) {
        pageClick = event.showWarning;
        if (event.content.equals("送谷电机超时")) {
            pageClick = false;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return pageClick;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        requireContext().unbindService(conn);
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }


    @OnClick({R.id.btnMemberRecharge, R.id.btnEnableCard})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.btnMemberRecharge:
                MachineContainer.isConsumption = false;
                final RechargeDialogF rechargeDialogF = new RechargeDialogF();
                rechargeDialogF.show(getChildFragmentManager(), RechargeDialogF.class.getSimpleName());

                break;

            case R.id.btnEnableCard:
                MachineContainer.isConsumption = false;
                final EnableCardDialogF enableCardDialogF = new EnableCardDialogF();
                enableCardDialogF.show(getChildFragmentManager(), EnableCardDialogF.class.getSimpleName());

                break;
        }
    }

}